import express from 'express'
import User from '../models/user'
import Friend from '../models/friend'
import Socket from "../models/socket";
import {sign, verify} from '../util/TokenUtil'
import {auth} from '../middleware'
import config from '../config'
import pinyin  from 'pinyin'
import Article from '../models/acticle'
import Comment from '../models/comment'
import ThumbUp from '../models/thumbup'
import {decrypt} from '../util/Tool'

const router = express.Router();

//登录
router.post('/login', async function (req, res, next) {

  const {username, password} = req.body;

  //数据校验
  if(username === ''){
    res.json({
      errno: 1,
      msg: '用户名不能为空'
    });
    return
  }

  if(password === ''){
    res.json({
      errno: 1,
      msg: '密码不能为空'
    });
    return
  }

  try{
    const userRes = await User.findOne({username})

    if(userRes){
      if(decrypt(userRes.password) !== decrypt(password)){
        res.json({
          errno: 1,
          msg: '密码不正确'
        })
      }else{

        const access_expire = config.access_expire
        const refresh_expire = config.refresh_expire
        const access_token = sign(userRes.id, access_expire)
        const refresh_token = sign(userRes.id, refresh_expire)
        res.json({
          errno: 0,
          data: {
            username: userRes.username,
            sex: userRes.sex,
            avatar: userRes.avatar,
            address: userRes.address,
            sign: userRes.sign,
            id: userRes.id,
            access_token,
            refresh_token,
            access_expire,
            refresh_expire
          },
          msg: '登录成功'
        })
      }
    }else{
      res.json({
        errno: 1,
        msg: '该用户未注册'
      })
    }

  }catch (e) {
    res.json({
      errno: 1,
      msg: '登录异常'
    })
  }

});

//注册
router.post('/register', async function (req, res, next) {

  const {username, password, passwordConfirm} = req.body;

  if(username === ''){
    res.json({
      errno: 1,
      msg: '用户名不能为空'
    });
    return
  }

  if(password === ''){
    res.json({
      errno: 1,
      msg: '密码不能为空'
    });
    return
  }


  try {
    const userRes = await User.findOne({username});

    if(userRes){
      res.json({
        errno: 1,
        msg: '用户名已存在'
      });
    }else{

      const letter = (pinyin(username[0])[0][0][0]).toUpperCase()
      let userModal = {
        username,
        password,
        letter,
      }

      const saveRes = await new User(userModal).save()
      if(saveRes){
        res.json({
          errno: 0,
          msg: '注册成功'
        })
      }else{
        res.json({
          errno: 1,
          msg: '注册失败'
        })
      }
    }

  } catch (e) {
    res.json({
      errno: 1,
      msg: '注册异常'
    })
  }

})


//退出
router.get('/loginOut', async function (req, res, next) {

  const userId = req.query.userId;
  try {
    const socketRes = await Socket.deleteOne({userId})

    if(socketRes){
      res.json({
        errno: 0,
        msg: '退出成功'
      })
    }else{
      res.json({
        errno: 1,
        msg: '退出失败'
      })
    }

  }catch (e) {
    res.json({
      errno: 1,
      msg: '退出异常'
    })
  }

})


router.post('/refreshToken', async function (req, res, next) {
  const refresh_token = req.body.refresh_token
  const reuslt = verify(refresh_token);
  if (reuslt.success) {
    const id = reuslt.decoded.userId
    const useRes = await User.findOne({_id: id})
    if(useRes){
      const access_expire = config.access_expire
      const access_token = sign(id, access_expire)

      res.json({
        errno: 0,
        data:{
          access_token,
          access_expire
        },
        msg: '刷新 Token 成功'
      })

    }else{
      res.json({
        errno: 1,
        msg: '授权用户不存在'
      })
    }
  } else {
    res.json({
      errno: 1,
      msg: '登录已失效'
    })
  }

})

router.post('/publishArticle', auth,async function (req, res, next) {
  const {userId, articleContent} = req.body

  const time = new Date().getTime()

  console.log(time)

  const article = {
    userId,
    articleContent,
    time
  }

  await new Article(article).save()

  res.json({
    errno: 0,
    msg: '发表成功'
  })

})

router.get('/getArticle', auth, async function (req, res, next) {

  const page = req.query.page
  const articles = await Article.find().populate({
    path: 'userId',
    select: 'username nickname avatar address letter'
  })
    .skip(page*10)
    .limit(10)
    .sort({'_id':-1});

  res.json({
    errno: 0,
    data: articles,
    msg: '获取成功'
  })

})

router.post('/comment', auth, async function (req, res, next) {
  const {userId, articleId, commentContent} = req.body

  const commentModal = {
    userId,
    articleId,
    commentContent
  }

  await new Comment(commentModal).save()

  res.json({
    errno: 0,
    msg: '评论成功'
  })

})

router.get('/getComment', auth, async function (req, res, next) {
  const articleId = req.query.articleId

  const comments = await Comment.find({articleId}).populate({
    path: 'userId',
    select: 'username nickname avatar address letter'
  })

  res.json({
    errno: 0,
    data: comments,
    msg: '获取评论成功'
  })

})


router.post('/thumbUp', auth, async function (req, res, next) {
  const {userId, articleId} = req.body

  const thumbModal = {
    userId,
    articleId,
  }

  const checkThumb = await ThumbUp.find(thumbModal)

  if (checkThumb.length !== 0) {
    res.json({
      errno: 1,
      msg: '您已经点过赞了'
    });
    return;
  }

  await new ThumbUp(thumbModal).save()

  res.json({
    errno: 0,
    msg: '点赞成功'
  })

})

router.post('/cancelThumbUp', auth, async function (req, res, next) {
  const {userId, articleId} = req.body

  const thumbModal = {
    userId,
    articleId,
  }

  const checkThumb = await ThumbUp.find(thumbModal)

  if (checkThumb.length !== 0) {
    await ThumbUp.remove(thumbModal)
  }

  res.json({
    errno: 0,
    msg: '取消成功'
  })

})

router.get('/getThumb', auth, async function (req, res, next) {
  const articleId = req.query.articleId

  const thumbs = await ThumbUp.find({articleId}).populate({
    path: 'userId',
    select: 'username nickname avatar address letter'
  })

  res.json({
    errno: 0,
    data: thumbs,
    msg: '获取点赞列表成功'
  })

})

router.post('/isThumbUp', auth, async function (req, res, next) {
  const {userId, articleId} = req.body

  const thumbModal = {
    userId,
    articleId,
  }

  const checkThumb = await ThumbUp.find(thumbModal)

  if (checkThumb.length !== 0) {
    res.json({
      errno: 0,
      msg: '已赞'
    });
  }else{
    res.json({
      errno: 0,
      msg: '未赞'
    });
  }

})


router.post('/changeAvatar', auth, async function (req, res, next) {
  const _id = req.body.userId
  const avatar = req.body.avatar
  const user = await User.updateOne({_id},{avatar})
  console.log(user)
  res.json({
    errno: 0,
    msg: '更新头像成功'
  })

})

router.post('/changeName', auth, async function (req, res, next) {
  const _id = req.body.userId
  const username = req.body.username

  await User.update({_id},{username})

  res.json({
    errno: 0,
    msg: '更新名字成功'
  })

})





export default router
